#include "mainwidget.h"
#include "ui_mainwidget.h"

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    ,m_itemCounter(0)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);
    setupUI();
    setupConnections();
    initData();
    setupStyles();
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::setupUI()
{
    // 创建表格视图
    m_tableView = new QTableView(this);
    m_tableModel = new CustomTablemodel(this);
    //设置模型
    m_tableView->setModel(m_tableModel);

    // 设置委托
    m_docTypeDelegate = new DocTypeDelegate(this);
    m_operationDelegate = new OperationDelegate(this);
    //设置委托为下拉框
    m_tableView->setItemDelegateForColumn(2, m_docTypeDelegate); // 文档类型列
    //设置第7列
    m_tableView->setItemDelegateForColumn(7, m_operationDelegate); // 操作列

    // 设置视图属性
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);//整行选择
    m_tableView->setAlternatingRowColors(true);//相邻行不同背景颜色
    m_tableView->setSortingEnabled(true);//启用排序功能
    m_tableView->horizontalHeader()->setStretchLastSection(true);//最后一列自动拉伸
    m_tableView->verticalHeader()->setVisible(false);//隐藏垂直表头
    m_tableView->setSelectionMode(QAbstractItemView::SingleSelection);//选择模式为单选

    // 设置列宽
    m_tableView->setColumnWidth(0, 60);   // 序号
    m_tableView->setColumnWidth(1, 150);  // 文件名
    m_tableView->setColumnWidth(2, 120);  // 文档类型
    m_tableView->setColumnWidth(3, 100);  // 文档格式
    m_tableView->setColumnWidth(4, 100);  // 大小
    m_tableView->setColumnWidth(5, 120);  // 创建时间
    m_tableView->setColumnWidth(6, 120);  // 更新时间
    m_tableView->setColumnWidth(7, 200);  // 操作

    // 创建按钮
    m_btnAdd = new QPushButton("添加项目", this);
    m_btnRemove = new QPushButton("删除选中", this);
    m_btnChangeStatus = new QPushButton("改变状态", this);
    m_btnAddIcon = new QPushButton("添加图标", this);

    // 按钮布局管理器 水平
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->addWidget(m_btnAdd);
    m_buttonLayout->addWidget(m_btnRemove);
    m_buttonLayout->addWidget(m_btnChangeStatus);
    m_buttonLayout->addWidget(m_btnAddIcon);
    //增加课伸缩空间
    m_buttonLayout->addStretch();
    //整体的布局管理器 垂直 为主窗口的主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->addLayout(m_buttonLayout);
    m_mainLayout->addWidget(m_tableView);
}


void MainWidget::setupStyles()
{
    // 设置应用程序样式
    QString styleSheet = R"(
        QWidget {
            font-family: "Microsoft YaHei", "Segoe UI", Arial;
            font-size: 14px;
        }

        QTableView {
            gridline-color: #d0d0d0;
            background-color: white;
            alternate-background-color: #f8f8f8;
            selection-background-color: #e3f2fd;
        }

        QHeaderView::section {
            background-color: #f0f0f0;
            padding: 8px;
            border: 1px solid #d0d0d0;
            font-weight: bold;
        }

        QPushButton {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            font-weight: bold;
            min-width: 80px;
        }

        QPushButton:hover {
            opacity: 0.9;
        }

        QPushButton:pressed {
            opacity: 0.8;
        }

        #m_btnAdd {
            background-color: #4CAF50;
            color: white;
        }

        #m_btnRemove {
            background-color: #f44336;
            color: white;
        }

        #m_btnChangeStatus {
            background-color: #FF9800;
            color: white;
        }

        #m_btnAddIcon {
            background-color: #2196F3;
            color: white;
        }
    )";
    // 为按钮设置对象名称以便样式表选择
    m_btnAdd->setObjectName("m_btnAdd");
    m_btnRemove->setObjectName("m_btnRemove");
    m_btnChangeStatus->setObjectName("m_btnChangeStatus");
    m_btnAddIcon->setObjectName("m_btnAddIcon");
    //设置主窗口的样式
    this->setStyleSheet(styleSheet);
}



void MainWidget::setupConnections()
{
    //进行信号槽的连接
    connect(m_btnAdd, &QPushButton::clicked, this, &MainWidget::onAddItem);
    connect(m_btnRemove, &QPushButton::clicked, this, &MainWidget::onRemoveItem);
    connect(m_btnChangeStatus, &QPushButton::clicked, this, &MainWidget::onChangeStatus);
    connect(m_btnAddIcon, &QPushButton::clicked, this, &MainWidget::onAddIcon);
    //我们的操作列的信号与槽的连接
    connect(m_operationDelegate, &OperationDelegate::uploadClicked, this, &MainWidget::onUploadClicked);
    connect(m_operationDelegate, &OperationDelegate::deleteClicked, this, &MainWidget::onDeleteClicked);
    connect(m_operationDelegate, &OperationDelegate::viewClicked, this, &MainWidget::onViewClicked);
}






//初始化我们的模型
void MainWidget::initData()
{
    // 添加附件中的数据
    TableItem item1;
    item1.fileName = "**********";
    item1.docType = InstallGuide;
    item1.docFormat = "txt";
    item1.size = "2M";
    item1.createTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item1.updateTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item1.status = 1;
    m_tableModel->addItem(item1);

    TableItem item2;
    item2.fileName = "说明文档";
    item2.docType = UserManual;
    item2.docFormat = "doc";
    item2.size = "158KB";
    item2.createTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item2.updateTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item2.status = 1;
    m_tableModel->addItem(item2);

    TableItem item3;
    item3.fileName = "安装指南";
    item3.docType = InstallGuide;
    item3.docFormat = "markdown";
    item3.size = "2M";
    item3.createTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item3.updateTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item3.status = 1;
    m_tableModel->addItem(item3);

    TableItem item4;
    item4.fileName = "设计文档";
    item4.docType = DesignDoc;
    item4.docFormat = "pdf";
    item4.size = "3M";
    item4.createTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item4.updateTime = QDateTime::fromString("2024-9-21", "yyyy-M-d");
    item4.status = 1;
    m_tableModel->addItem(item4);
}



void MainWidget::onAddItem()
{
    TableItem item;
    item.fileName = QString("新文件%1").arg(++m_itemCounter);
    item.docType = OtherDoc;
    item.docFormat = "txt";
    item.size = "1M";
    item.createTime = QDateTime::currentDateTime();
    item.updateTime = QDateTime::currentDateTime();
    item.status = 0;

    m_tableModel->addItem(item);
    //%1占位符 用文件名代替
    QMessageBox::information(this, "添加成功",
                             QString("已添加新文件: %1").arg(item.fileName));
}


void MainWidget::onRemoveItem()
{
    QModelIndexList selected = m_tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的行！");
        return;
    }

    int ret = QMessageBox::question(this, "确认删除",
                                    QString("确定要删除选中的 %1 个项目吗?").arg(selected.size()),
                                    QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        // 从后往前删除，避免索引变化
        for (int i = selected.size() - 1; i >= 0; --i) {
            m_tableModel->removeItem(selected.at(i).row());
        }

        QMessageBox::information(this, "删除成功",
                                 QString("已删除 %1 个项目").arg(selected.size()));
    }
}

void MainWidget::onChangeStatus()
{
    //拿到选中行 QModelIndex返回的列都是0
    QModelIndexList selected = m_tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要改变状态的行！");
        return;
    }
    //遍历选中行的每一行
    for (const QModelIndex &index : selected) {
        TableItem item = m_tableModel->getItem(index.row());
        int newStatus = (item.status + 1) % 4; // 循环切换状态 0-3
        m_tableModel->setItemStatus(index.row(), newStatus);
    }

    QMessageBox::information(this, "状态更新",
                             QString("已更新 %1 个项目的状态").arg(selected.size()));
}

void MainWidget::onAddIcon()
{
    QModelIndexList selected = m_tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要添加图标的行！");
        return;
    }

    // 使用系统图标作为示例
    QIcon icon = QApplication::style()->standardIcon(QStyle::SP_FileIcon);
    for (const QModelIndex &index : selected) {
        m_tableModel->setItemIcon(index.row(), icon);
    }

    QMessageBox::information(this, "图标添加",
                             QString("已为 %1 个项目添加图标").arg(selected.size()));
}

void MainWidget::onUploadClicked(int row)
{
    TableItem item = m_tableModel->getItem(row);
    //弹框
    QString fileName = QFileDialog::getOpenFileName(this, "选择要上传的文件", "", "所有文件 (*)");
    if (!fileName.isEmpty()) {
        QMessageBox::information(this, "上传文件",
                                 QString("正在上传文件到服务器:\n"
                                         "本地文件: %1\n"
                                         "目标位置: %2")
                                     .arg(fileName)
                                     .arg(item.fileName));
    }
}

void MainWidget::onDeleteClicked(int row)
{
    TableItem item = m_tableModel->getItem(row);
    int ret = QMessageBox::question(this, "确认删除",
                                    QString("确定要删除文件 '%1' 吗?\n\n"
                                            "类型: %2\n格式: %3\n大小: %4")
                                        .arg(item.fileName)
                                        .arg(CustomTablemodel::docTypeToString(item.docType))
                                        .arg(item.docFormat)
                                        .arg(item.size),
                                    QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        m_tableModel->removeItem(row);
        QMessageBox::information(this, "删除成功", "文件已删除");
    }
}

void MainWidget::onViewClicked(int row)
{
    TableItem item = m_tableModel->getItem(row);
    QMessageBox::information(this, "文件详情",
                             QString("文件名: %1\n"
                                     "文档类型: %2\n"
                                     "文档格式: %3\n"
                                     "文件大小: %4\n"
                                     "创建时间: %5\n"
                                     "更新时间: %6")
                                 .arg(item.fileName)
                                 .arg(CustomTablemodel::docTypeToString(item.docType))
                                 .arg(item.docFormat)
                                 .arg(item.size)
                                 .arg(item.createTime.toString("yyyy-MM-dd hh:mm:ss"))
                                 .arg(item.updateTime.toString("yyyy-MM-dd hh:mm:ss")));
}
